import os
import json
from pymdi import pymdi
import requests
import re
import yaml

# https://cdi-web.cla-dev.mmtdev.com/cdi/token
# 先获取自己的token, 点击下 reset
token_self_ = "dcdad927-a278-4fad-95ea-f3e8f0c1cca7"
json_ = {}

# 1. input bag md5


def get_bag_info_md5(mdc5):
    client = pymdi.Client(token=token_self_)
    md5_list = [mdc5]
    result = client.get_meta(md5_list)
    if len(result) == 0:
        return
    # 区分dfdi 还是cfdi
    fdi_type = client.get_meta(md5_list)[0]["asset"]["fdi_type"]
    if fdi_type == "CFDI":
        try:
            json_["bag_name"] = client.get_meta(md5_list)[0]["name"]
            json_["bag_md5"] = mdc5
            json_["business_type"] = client.get_meta(
                md5_list)[0]["custom_meta"]["project_name"]
            json_["car_type"] = client.get_meta(
                md5_list)[0]["custom_meta"]["car_type"]
            deploy = client.get_meta(
                md5_list)[0]["custom_meta"]["mass_production"]["system_name"]
            json_["car_plate"] = client.get_meta(
                md5_list)[0]["custom_meta"]["mass_production"]["vin"]
            get_bag_info_deploy(deploy, 0)
        except:
            return
    else:
        # 异常处理
        try:
            json_["business_type"] = client.get_meta(
                md5_list)[0]["fdi"]["fmp"]["car_info"]["business_type"]
            json_["car_type"] = client.get_meta(
                md5_list)[0]["fdi"]["fmp"]["car_info"]["car_type"]
            json_["car_plate"] = client.get_meta(
                md5_list)[0]["fdi"]["fmp"]["car_info"]["car_plate"]

            modules = client.get_meta(
                md5_list)[0]["fdi"]["soft_version_v2"]["modules_version"]
            for module in modules:
                if "vehicle_service" in module["name"]:
                    json_["branch"] = module["branch"]
                    json_["commit"] = module["commit"]
                    json_["name"] = module["name"]

            parse_metas = client.parse_meta(md5_list)
            json_["bag_name"] = parse_metas[0]["bag_name"]
            json_["bag_md5"] = mdc5

            deploy = client.get_meta(
                md5_list)[0]["fdi"]["soft_version_v2"]["packages_version"][0]["version"]
            get_bag_info_deploy(deploy, 1)
        except:
            return
# input 为deploy


def get_bag_info_deploy(deploy, flag=0):
    payload = {'package_name': deploy}
    response = requests.get(
        'https://ep.momenta.works/backend/package-meta/api/v1/metas', params=payload)
    # print(response.json())
    res_json = response.json()
    # print("res_json:", res_json)
    # print("res_text:", response.text)
    if (res_json["status"] == 20002):
        json_["status"] = 0
        return
    try:
        for array in res_json["data"]["meta"]:
            if "version_file_url" == array["key"]:
                resp = requests.get(array["value"])
                # print("json", resp.json())
                json_["mf_system_branch"] = resp.json()["branch"]
                json_["mf_system_commit_id"] = resp.json()["commit_id"]
                json_["deploy"] = deploy
        if flag == 0:
            for array in res_json["data"]["meta"]:
                if "reproduction_yaml_file_url" == array["key"]:
                    # print(array["value"])
                    resp = requests.get(array["value"])
                    data = yaml.safe_load(resp.content)
                    # print("data", data)
                    for module in data["modules"]:
                        # print("modules:", module["name"])
                        if "vehicle_service" in module["name"]:
                            # print("modules_vehicle_service:", module["name"])
                            json_["branch"] = module["git_branch_old"]
                            json_["commit"] = module["git_commit"]
                            json_["name"] = module["name"]
                if "project_name" == array["key"]:
                    json_["business_type"] = array["value"]
        json_["status"] = 1
    except:
        return

# input 为bagfile


def get_bag_info_bagfile(bagfile):
    body = {
        "query": {
            "bool": {
                "must": [
                    {
                        "name": bagfile
                    }
                ],
                "must_not": []
            }
        },
        "sort": "create_time:desc",
        "meta_type": "bag",
        "limit": 10000
    }
    resp = requests.post("https://data.momenta.works/api/v2/search/meta",
                         headers={"Authorization": token_self_}, json=body)
    if (resp.json()["total"] == 0):
        return
    resp_md5 = resp.json()["data"][0]
    get_bag_info_md5(resp_md5)


def get_input(input):
    pattern_md5 = r'^[a-f0-9]{32}$'
    pattern_bagfile = r'.*\.bag$'
    pattern_tgzfile = r'.*\.tgz$'
    #  清空json
    json_.clear()

    if re.match(pattern_md5, input):
        get_bag_info_md5(input)
        print('This is an md5 hash value.')
    elif re.match(pattern_bagfile, input):
        get_bag_info_bagfile(input)
        print('This is a .bag file name.')
    elif re.match(pattern_tgzfile, input):
        get_bag_info_deploy(input)
        print('This is a .tgz file name.')
    else:
        print('Unrecognized input.')
        json_["status"] = 0


def get_info_json():
    return json_
